package concurrent.write;

import eventHandle.ServiceHandle;
import radio.ServerListener;
import http.Request;
import http.Response;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

/** 读线程池
 * Created by zzf on 2017/4/26.
 */
public class Writer extends Thread {
    private static final String THREAD_NAME = "write-thread-";
    private static AtomicInteger number = new AtomicInteger(0);
    private SelectionKey key;
    private byte[] outputData;
    private Future<Request> future;
    private ServerListener serverListener = new ServiceHandle();
    public Writer(SelectionKey key, Future<Request> future)  {
        //自定义线程名字
        super(THREAD_NAME+number.incrementAndGet());

        this.key = key;
        this.future = future;

    }

    @Override
    public void run() {

        SocketChannel channel = (SocketChannel) key.channel();

        try {

            Request request = future.get(20, TimeUnit.SECONDS);
            System.out.println("开始写--------");
            outputData = request.getInputData();

            Response response = new Response(channel,outputData);


            serverListener.onWrite(response);
            System.out.println("写完了--------");

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
            Response response = new Response(channel,"超时".getBytes());
            try {
                serverListener.onWrite(response);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            System.out.println("超时-----");
        }
    }
}
